// packageAPI/pages/map/map.js
Page({
  data: {
    title: '',
    zh: '',
    webUrl: '',
    schema: {
      groups: []
    },
    formData: {},
    result: '',
    // 确保currentLocation始终有默认值
    currentLocation: {
      latitude: 39.9042,
      longitude: 116.4074
    },
    // 地图中心点位置
    currentCenterLocation: null,
    // 当前地图范围
    currentRegion: null,
    // 当前地图旋转角度
    currentRotate: null,
    // 当前地图缩放级别
    currentScale: null,
    apiName: "",
    // 当前地图倾斜角度
    currentSkew: null,
    // 地图中心点偏移 [x, y]，默认[0.5, 0.5]
    centerOffset: [0.5, 0.5],
    // 定位标记图标配置
    locMarkerIcon: {
      iconPath: '/image/location.png',
      width: 30,
      height: 30
    },
    markers: [],
    polyline: [],
    circles: [],
    controls: [],
    includePoints: [],
    groundOverlays: [],
    arcs: [],
    visualLayers: [],
    mapContext: null
  },

  onLoad: function (options) {
    console.log('Map页面加载');
    console.log('路由传递的参数:', options);
    
    // 处理路由参数
    if (options) {
      const routeData = {
        zh: options.zh ,           
        title: options.title ,       
        remark: options.remark ,
        webUrl: options.webUrl    
      };
      
      this.setData({  
        title: routeData.title,       
        zh: routeData.zh,
        webUrl: routeData.webUrl,
        apiName: routeData.zh,
        result: `页面加载完成 - ${routeData.title}`
      });
    } else {
      this.setData({
        title: 'Map API',                           
        zh: 'Map API',
        webUrl: '',
        apiName: 'Map API',
        result: '页面加载完成 - 使用默认配置'
      });
    }

    // 确保currentLocation有默认值
    if (!this.data.currentLocation || !this.data.currentLocation.latitude) {
      this.setData({
        currentLocation: {
          latitude: 39.9042,
          longitude: 116.4074
        }
      });
    }

    // 初始化地图上下文
    this.mapContext = wx.createMapContext('myMap',this);
    // 初始化事件监听器
    this.initEventListeners();

    // 获取当前位置
    this.getUserLocation();

    // 添加地图控件
    this.addMapControls();
    
    // 自动添加商店标记点
    const storeMarker = {
      id: 1, // 使用数字ID
      latitude: 39.9042 + 0.05, // 在北京附近添加一个商店，距离更远一些
      longitude: 116.4074 + 0.05,
      title: '鸭首领(苏州绿宝广场店)',
      iconPath: '/image/record.png', // 使用默认图标
      width: 50,
      height: 50,
      callout: {
        content: '鸭首领(苏州绿宝广场店)\n长江路436号绿宝休闲广场5幢133号',
        display: 'ALWAYS', // 始终显示气泡
        fontSize: 14,
        borderRadius: 8,
        padding: 10,
        bgColor: '#333333',
        borderWidth: 1,
        borderColor: '#666666',
        color: '#ffffff'
      },
      // 商店详细信息
      storeInfo: {
        name: '鸭首领(苏州绿宝广场店)',
        address: '长江路436号绿宝休闲广场5幢133号',
        phone: '0512-12345678',
        businessHours: '09:00-22:00',
        category: '餐饮',
        cuisine: '甜辣卤味|麻辣烫',
        rating: 4.5,
        priceRange: '¥20-50'
      }
    };

    // 将商店标记点添加到markers数组中
    const markers = this.data.markers || [];
    markers.push(storeMarker);
    
    // 更新include-points，确保商店标记点可见
    const includePoints = [
      { latitude: this.data.currentLocation.latitude, longitude: this.data.currentLocation.longitude },
      { latitude: storeMarker.latitude, longitude: storeMarker.longitude }
    ];
    
    this.setData({
      markers: markers,
      includePoints: includePoints
    });

  },
  // API处理函数
  handleApiCall: function (e) {
    const apiName = e.currentTarget.dataset.apiname;

    this.setData({
      apiName: apiName
    });

    switch (apiName) {
      case 'wx.createMapContext':
        this.createMapContextFunc();
        break;
      case 'wx.getLocation':
        this.getLocationFunc();
        break;
      case 'wx.chooseLocation':
        this.chooseLocationFunc();
        break;
      case 'wx.openLocation':
        this.openLocationFunc();
        break;
      case 'MapContext.setCenterOffset':
        this.setCenterOffsetFunc();
        break;
      case 'MapContext.setLocMarkerIcon':
        this.setLocMarkerIconFunc();
        break;
      case 'MapContext.toScreenLocation':
        this.toScreenLocationFunc();
        break;
      case 'MapContext.updateGroundOverlay':
        this.updateGroundOverlayFunc();
        break;
      default:
        this.showResult(`未知的API: ${apiName}`);
    }
  },

  // 创建地图上下文
  createMapContextFunc: function () {
    try {
      this.mapContext = wx.createMapContext('myMap');
      this.showResult(
        this.mapContext
      );
    } catch (error) {
      console.error('地图上下文创建失败:', error);
      this.showResult({
        success: false,
        message: '地图上下文创建失败',
        error: error
      });
    }
  },

  // 获取位置信息
  getLocationFunc: function () {
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          currentLocation: res
        });
        that.showResult({
          success: true,
          message: '位置获取成功',
          location: res
        });
      },
      fail: function (err) {
        console.error('位置获取失败:', err);
        that.showResult({
          success: false,
          message: '位置获取失败',
          error: err
        });
      }
    });
  },

  // 选择位置
  chooseLocationFunc: function () {
    const that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          currentLocation: res
        });
        that.showResult({
          success: true,
          message: '位置选择成功',
          location: res
        });
      },
      fail: function (err) {
        console.error('位置选择失败:', err);
        that.showResult({
          success: false,
          message: '位置选择失败',
          error: err
        });
      }
    });
  },

  // 打开位置
  openLocationFunc: function () {
    const that = this;
    if (!that.data.currentLocation) {
      that.showResult({
        success: false,
        message: '请先获取位置信息'
      });
      return;
    }

    wx.openLocation({
      latitude: that.data.currentLocation.latitude,
      longitude: that.data.currentLocation.longitude,
      name: '当前位置',
      address: '当前位置',
      success: function (res) {
        that.showResult({
          success: true,
          message: '打开位置成功',
          result: res
        });
      },
      fail: function (err) {
        console.error('打开位置失败:', err);
        that.showResult({
          success: false,
          message: '打开位置失败',
          error: err
        });
      }
    });
  },

  // 设置地图中心点偏移
  setCenterOffsetFunc: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 使用默认偏移值进行测试
    const offsetParams = {
      offset: [0.6, 0.6], // 向右下偏移
      success: function (result) {
        that.showResult(
          result
        );
      },
      fail: function (error) {
        that.showResult(
          error
        );
      }
    };

    that.mapContext.setCenterOffset(offsetParams);

  },

  // 设置定位标记图标
  setLocMarkerIconFunc: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 使用默认参数进行测试
    const iconParams = {
      iconPath: '/image/pause.png',
      width: 40,
      height: 40,
      success: function (result) {
        that.showResult({
          result
        });
      },
      fail: function (error) {
        that.showResult({
          success: false,
          message: '设置定位标记图标失败',
          error: error.errMsg
        });
      }
    };

    that.setLocMarkerIcon(iconParams);
  },

  // 地图坐标转换为屏幕坐标
  toScreenLocationFunc: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 使用当前位置进行测试
    const currentLocation = that.data.currentLocation;
    if (!currentLocation || !currentLocation.latitude) {
      that.showResult('请先获取位置信息');
      return;
    }

    const screenParams = {
      latitude: currentLocation.latitude,
      longitude: currentLocation.longitude,
      success: function (result) {
        that.showResult({
          result
        });
      },
      fail: function (error) {
        that.showResult({
          success: false,
          message: '地图坐标转换为屏幕坐标失败',
          error: error.errMsg
        });
      }
    };

    that.toScreenLocation(screenParams);
  },

  // 更新地面覆盖物
  updateGroundOverlayFunc: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 检查是否有地面覆盖物
    const groundOverlays = that.data.groundOverlays || [];
    if (groundOverlays.length === 0) {
      that.showResult('请先添加地面覆盖物');
      return;
    }

    // 使用第一个地面覆盖物进行测试
    const overlay = groundOverlays[0];

    // 更新地面覆盖物属性
    const updateParams = {
      id: overlay.id,
      opacity: 0.8, // 更新透明度
      rotate: 45,   // 更新旋转角度
      visible: true, // 确保可见
      success: function (result) {
        that.showResult(
          result
        );
      },
      fail: function (error) {
        that.showResult(`地面覆盖物更新失败: ${error.errMsg}`);
      }
    };

    that.updateGroundOverlay(updateParams);
  },

  // 标记点移动动画
  translateMarkerFunc: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 检查是否有标记点
    const markers = that.data.markers || [];
    if (markers.length === 0) {
      that.showResult('请先添加标记点');
      return;
    }

    // 使用第一个标记点进行测试
    const marker = markers[0];
    const currentLocation = that.data.currentLocation;

    if (!currentLocation || !currentLocation.latitude) {
      that.showResult('请先获取位置信息');
      return;
    }

    const translateParams = {
      markerId: marker.id,
      destination: {
        latitude: currentLocation.latitude + 0.01,
        longitude: currentLocation.longitude + 0.01
      },
      duration: 2000,
      autoRotate: true,
      success: function (result) {
        that.showResult({
          success: true,
          message: '标记点移动动画成功',
          markerId: result.markerId,
          destination: result.destination,
          duration: result.duration,
          autoRotate: result.autoRotate,
          description: result.description
        });
      },
      fail: function (error) {
        that.showResult({
          success: false,
          message: '标记点移动动画失败',
          error: error.errMsg
        });
      }
    };

    that.translateMarker(translateParams);
  },

  // 标记点移动动画
  translateMarker: function (object) {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    // 验证标记点ID
    if (!object.markerId && object.markerId !== 0) {
      console.error('markerId不能为空');
      return { errMsg: 'markerId不能为空' };
    }

    // 验证目标位置
    if (typeof object.destination !== 'object' || !object.destination) {
      console.error('destination必须是对象类型');
      return { errMsg: 'destination必须是对象类型' };
    }

    if (typeof object.destination.latitude !== 'number' || typeof object.destination.longitude !== 'number') {
      console.error('destination.latitude和destination.longitude必须是数字类型');
      return { errMsg: 'destination.latitude和destination.longitude必须是数字类型' };
    }

    // 验证经纬度范围
    if (object.destination.latitude < -90 || object.destination.latitude > 90) {
      console.error('目标纬度必须在-90到90之间');
      return { errMsg: '目标纬度必须在-90到90之间' };
    }

    if (object.destination.longitude < -180 || object.destination.longitude > 180) {
      console.error('目标经度必须在-180到180之间');
      return { errMsg: '目标经度必须在-180到180之间' };
    }

    // 验证动画参数
    const duration = object.duration || 1000; // 默认1秒
    const autoRotate = object.autoRotate || false; // 默认不自动旋转

    if (typeof duration !== 'number' || duration <= 0) {
      console.error('duration必须是大于0的数字');
      return { errMsg: 'duration必须是大于0的数字' };
    }

    if (typeof autoRotate !== 'boolean') {
      console.error('autoRotate必须是布尔类型');
      return { errMsg: 'autoRotate必须是布尔类型' };
    }

    try {
      // 在实际环境中，这里应该调用微信小程序的原生MapContext.translateMarker方法
      // 由于这是一个模拟实现，我们将模拟标记点移动动画


      // 查找对应的标记点
      const markers = that.data.markers || [];
      const markerIndex = markers.findIndex(marker => marker.id === object.markerId);

      if (markerIndex === -1) {
        console.error('未找到指定的标记点');
        return { errMsg: '未找到指定的标记点' };
      }

      const currentMarker = markers[markerIndex];
      const startLat = currentMarker.latitude;
      const startLng = currentMarker.longitude;
      const endLat = object.destination.latitude;
      const endLng = object.destination.longitude;

      // 计算移动距离
      const deltaLat = endLat - startLat;
      const deltaLng = endLng - startLng;

      // 动画参数
      const startTime = Date.now();
      const animationDuration = duration;
      const frameRate = 60; // 60fps
      const frameInterval = 1000 / frameRate;

      // 创建动画函数
      const animateMarker = () => {
        const currentTime = Date.now();
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / animationDuration, 1);

        // 使用缓动函数 (ease-out)
        const easeProgress = 1 - Math.pow(1 - progress, 3);

        // 计算当前位置
        const currentLat = startLat + deltaLat * easeProgress;
        const currentLng = startLng + deltaLng * easeProgress;

        // 更新标记点位置
        const updatedMarkers = [...markers];
        updatedMarkers[markerIndex] = {
          ...updatedMarkers[markerIndex],
          latitude: currentLat,
          longitude: currentLng
        };

        that.setData({
          markers: updatedMarkers
        });

        // 如果动画未完成，继续下一帧
        if (progress < 1) {
          setTimeout(animateMarker, frameInterval);
        } else {
          // 动画完成
          const result = {
            errMsg: 'translateMarker:ok',
            markerId: object.markerId,
            destination: object.destination,
            duration: duration,
            autoRotate: autoRotate,
            description: `标记点${object.markerId}已移动到位置(${object.destination.latitude.toFixed(6)}, ${object.destination.longitude.toFixed(6)})`
          };


          // 调用成功回调
          if (object.success && typeof object.success === 'function') {
            object.success(result);
          }
        }
      };

      // 开始动画
      animateMarker();

      const result = {
        errMsg: 'translateMarker:ok',
        markerId: object.markerId,
        destination: object.destination,
        duration: duration,
        autoRotate: autoRotate,
        description: `标记点${object.markerId}开始移动到位置(${object.destination.latitude.toFixed(6)}, ${object.destination.longitude.toFixed(6)})`
      };

      return result;
    } catch (error) {
      console.error('标记点移动动画异常', error);
      const errorResult = { errMsg: `translateMarker:fail ${JSON.stringify(error)}` };

      // 调用失败回调
      if (object.fail && typeof object.fail === 'function') {
        object.fail(errorResult);
      }

      return errorResult;
    }
  },

  // 初始化事件监听器
  initEventListeners: function () {
    const that = this;

    // 监听可视化图层更新事件
    if (that.mapContext && typeof that.mapContext.on === 'function') {
      that.mapContext.on('visualLayerUpdate', function (res) {
        that.onVisualLayerUpdate(res);
      });

      that.mapContext.on('visualLayerCommand', function (res) {
        that.onVisualLayerCommand(res);
      });

      that.mapContext.on('visualLayerError', function (res) {
        that.onVisualLayerError(res);
      });

    } else {
      console.warn('MapContext.on方法不可用，使用模拟事件监听');
      // 在模拟环境中，我们手动管理事件
      that.eventListeners = {
        visualLayerUpdate: [],
        visualLayerCommand: [],
        visualLayerError: []
      };
    }
  },

  // 可视化图层更新事件处理
  onVisualLayerUpdate: function (res) {
    this.showResult(`可视化图层更新: ${JSON.stringify(res)}`);

    // 更新本地数据
    if (res && res.layerId) {
      const visualLayers = this.data.visualLayers || [];
      const layerIndex = visualLayers.findIndex(layer => layer.id === res.layerId);

      if (layerIndex !== -1 && res.data) {
        visualLayers[layerIndex] = {
          ...visualLayers[layerIndex],
          ...res.data
        };

        this.setData({
          visualLayers: visualLayers
        });
      }
    }
  },

  // 可视化图层指令事件处理
  onVisualLayerCommand: function (res) {
    this.showResult(`可视化图层指令执行: ${JSON.stringify(res)}`);
  },


  removeArcFunc: function () {
    const that = this;
    
    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }
  
    // 检查是否有弧线可以移除
    const currentArcs = that.data.arcs || [];
    if (currentArcs.length === 0) {
      that.showResult('当前没有弧线可以移除');
      return;
    }
  
    // 使用第一个弧线进行测试
    const firstArc = currentArcs[0];
    
    // 直接使用原生API
    that.mapContext.removeArc({
      id: firstArc.id,
      success: function(result) {
        // 更新本地数据
        const updatedArcs = currentArcs.filter(arc => arc.id !== firstArc.id);
        that.setData({
          arcs: updatedArcs
        });
        
        that.showResult(result);
      },
      fail: function(error) {
        that.showResult(error);
      }
    });
  },
  
  // 可视化图层错误事件处理
  onVisualLayerError: function (res) {
    console.error('可视化图层错误事件:', res);
    this.showResult(`可视化图层错误: ${JSON.stringify(res)}`);
  },

  // 获取用户位置
  getUserLocation: function () {
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: function (res) {
        const latitude = res.latitude;
        const longitude = res.longitude;

        that.setData({
          currentLocation: {
            latitude: latitude,
            longitude: longitude
          }
        });

        // 在当前位置添加标记
        that.addMarker(latitude, longitude, '当前位置', 0);
      },
      fail: function (err) {
        console.error('获取位置失败', err);
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      }
    });
  },

  // 添加地图控件
  addMapControls: function () {
    this.setData({
      controls: [
        {
          id: 1,
          iconPath: '/image/location.png',
          position: {
            left: 20,
            top: 100,
            width: 40,
            height: 40
          },
          clickable: true
        }
      ]
    });
  },

  // 添加标记点
  addMarker: function (latitude, longitude, title, id) {
    const marker = {
      id: id,
      latitude: latitude,
      longitude: longitude,
      title: title,
      iconPath: '/image/location.png',
      width: 30,
      height: 30,
      callout: {
        content: title,
        display: 'BYCLICK',
        fontSize: 12,
        borderRadius: 4,
        padding: 5
      }
    };

    const markers = this.data.markers;
    markers.push(marker);

    this.setData({
      markers: markers
    });
    this.showResult(markers);
  },

  // 添加圆形覆盖物
  addCircle: function (latitude, longitude, radius) {
    const circle = {
      latitude: latitude,
      longitude: longitude,
      radius: radius,
      strokeWidth: 2,
      strokeColor: '#007aff',
      fillColor: 'rgba(0, 122, 255, 0.1)'
    };

    const circles = this.data.circles;
    circles.push(circle);

    this.setData({
      circles: circles
    });
  },

  // 添加路线
  addPolyline: function (points) {
    const polyline = [{
      points: points,
      color: '#007aff',
      width: 4,
      dottedLine: false,
      arrowLine: true
    }];

    this.setData({
      polyline: polyline
    });
  },

  // 地图点击事件
  onMapTap: function (e) {
    const { latitude, longitude } = e.detail;
    // 使用时间戳作为唯一ID，避免与商店标记点冲突
    const newId = 'click_' + Date.now();
    this.addMarker(latitude, longitude, '点击位置', newId);
    this.showResult(this.data.markers[this.data.markers.length - 1]);
  },

  // 标记点点击事件
  onMarkerTap: function (e) {
    const { markerId } = e.detail;
    
    console.log('点击的标记点ID:', markerId, '类型:', typeof markerId);
    
    // 查找对应的标记点
    const marker = this.data.markers.find(m => m.id == markerId);
    
    if (marker && marker.storeInfo) {
      // 如果是商店标记点，更新气泡显示详细信息
      const storeInfo = marker.storeInfo;
      const detailedContent = `${storeInfo.name}\n${storeInfo.address}\n电话: ${storeInfo.phone}\n营业时间: ${storeInfo.businessHours}\n评分: ${storeInfo.rating}⭐`;
      
      // 更新标记点的气泡内容
      const updatedMarkers = this.data.markers.map(m => {
        if (m.id == markerId) {
          return {
            ...m,
            callout: {
              ...m.callout,
              content: detailedContent,
              display: 'ALWAYS',
              className: 'map-callout map-callout-text' // 使用CSS类名设置样式
            }
          };
        }
        return m;
      });
      
      this.setData({
        markers: updatedMarkers
      });
      
      console.log('已更新商店标记点气泡信息');
    } else {
      // 普通标记点
      console.log('点击普通标记点');
    }
  },

  // 地图区域变化事件
  onRegionChange: function (e) {
    const { type } = e.detail;
    if (type === 'end') {
      const that = this;

      // 检查地图上下文是否初始化
      if (!that.mapContext) {
        console.error('地图上下文未初始化');
        return;
      }

      that.mapContext.getCenterLocation({
        success: function (res) {
          // 检查返回数据是否有效
          if (res && typeof res.latitude === 'number' && typeof res.longitude === 'number') {
            // 不在这里显示结果，避免频繁触发
          } else {
            console.warn('获取地图中心点返回数据格式异常', res);
          }
        },
        fail: function (err) {
          console.error('获取地图中心点失败', err);
        }
      });
    }
  },

  // 控件点击事件
  onControlTap: function (e) {
    const { controlId } = e.detail;
    if (controlId === 1) {
      const that = this;
      // 检查是否有标记点
      if (that.data.markers.length === 0) {
        that.showResult('没有标记点可显示');
        return;
      }

      that.mapContext.includePoints({
        points: that.data.markers.map(marker => ({ latitude: marker.latitude, longitude: marker.longitude })),
        success: (res) => {
          that.showResult(res);

        },
        fail: (err) => {
          console.error('调整视野失败', err);
          that.showResult(`调整视野失败: ${err.errMsg}`);
        }
      });
    }
  },

  // 标记点气泡点击事件
  onCalloutTap: function (e) {
    const { markerId } = e.detail;
    this.showResult(`点击标记点气泡: ID=${markerId}`);
  },

  // 地图更新事件
  onMapUpdated: function () {
  },

  // POI点击事件
  onPoiTap: function (e) {
    const { name, address, latitude, longitude } = e.detail;
    this.showResult(`点击POI: ${name}, 地址: ${address}`);
  },

  // 锚点点击事件
  onAnchorPointTap: function (e) {
    const { markerId } = e.detail;
    this.showResult(`点击锚点: ID=${markerId}`);
  },

  // 清除所有标记
  clearMarkers: function () {
    this.setData({
      markers: []
    });
    this.showResult('已清除所有标记');
  },

  // 清除所有圆形覆盖物
  clearCircles: function () {
    this.setData({
      circles: []
    });
    this.showResult('已清除所有圆形覆盖物');
  },

  // 清除所有路线
  clearPolyline: function () {
    this.setData({
      polyline: []
    });
    this.showResult('已清除所有路线');
  },

  // 移动到当前位置
  moveToLocation: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.moveToLocation({
      success: (res) => {
        that.showResult(res);
      },
      fail: (err) => {
        that.showResult(err);
      }
    });
  },

  // 获取地图中心点
  getCenterLocation: function () {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getCenterLocation({
      success: function (res) {
        // 确保返回的是 gcj02 坐标系数据
        const centerLocation = {
          latitude: res.latitude,
          longitude: res.longitude,
          coordinateType: 'gcj02', // 明确标识坐标系类型
          timestamp: Date.now()
        };

        that.showResult(res);

        // 更新当前中心点数据
        that.setData({
          currentCenterLocation: centerLocation
        });

      },
      fail: function (err) {
        that.showResult(`获取地图中心点失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('获取地图中心点失败:', err);
      }
    });
  },

  // 获取地图范围
  getRegion: function () {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getRegion({
      success: function (res) {
        // 处理返回的地图范围数据
        const regionData = {
          southwest: {
            latitude: res.southwest.latitude,
            longitude: res.southwest.longitude
          },
          northeast: {
            latitude: res.northeast.latitude,
            longitude: res.northeast.longitude
          },
          center: {
            latitude: (res.southwest.latitude + res.northeast.latitude) / 2,
            longitude: (res.southwest.longitude + res.northeast.longitude) / 2
          },
          width: res.northeast.longitude - res.southwest.longitude,
          height: res.northeast.latitude - res.southwest.latitude,
          timestamp: Date.now()
        };

        // 显示详细的地图范围信息
        that.showResult(
          res
        );

        // 保存地图范围数据
        that.setData({
          currentRegion: regionData
        });

      },
      fail: function (err) {
        that.showResult(`获取地图范围失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('获取地图范围失败:', err);
      }
    });
  },

  // 获取地图旋转角度
  getRotate: function () {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }
    that.mapContext.getRotate({
      success: function (res) {
        const rotateData = {
          rotate: res.rotate,
          timestamp: Date.now()
        };

        that.showResult(
          `地图旋转角度: ${rotateData.rotate.toFixed(2)}°\n` +
          `获取时间: ${new Date(rotateData.timestamp).toLocaleString()}`
        );

        that.setData({
          currentRotate: rotateData
        });
      },
      fail: function (err) {
        that.showResult(`获取地图旋转角度失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('获取地图旋转角度失败:', err);
      }
    });
  },

  // 获取地图缩放级别
  getScale: function () {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getScale({
      success: function (res) {
        // 处理返回的缩放级别数据
        const scaleData = {
          scale: res.scale || 16, // 缩放级别
          timestamp: Date.now()
        };

        // 显示缩放级别信息
        that.showResult(
          `地图缩放级别: ${scaleData.scale}\n` +
          `缩放描述: ${that.getScaleDescription(scaleData.scale)}\n` +
          `获取时间: ${new Date(scaleData.timestamp).toLocaleString()}`
        );

        // 保存缩放级别数据
        that.setData({
          currentScale: scaleData
        });

      },
      fail: function (err) {
        that.showResult(`获取地图缩放级别失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('获取地图缩放级别失败:', err);
      }
    });
  },

  // 获取地图倾斜角度
  getSkew: function () {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getSkew({
      success: function (res) {
        // 处理返回的倾斜角度数据
        const skewData = {
          skew: res.skew || 0, // 倾斜角度（度）
          timestamp: Date.now()
        };

        // 显示倾斜角度信息
        that.showResult(
          `地图倾斜角度: ${skewData.skew.toFixed(2)}°\n` +
          `倾斜描述: ${that.getSkewDescription(skewData.skew)}\n` +
          `获取时间: ${new Date(skewData.timestamp).toLocaleString()}`
        );

        // 保存倾斜角度数据
        that.setData({
          currentSkew: skewData
        });

      },
      fail: function (err) {
        that.showResult(`获取地图倾斜角度失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('获取地图倾斜角度失败:', err);
      }
    });
  },

  // 获取倾斜角度描述
  getSkewDescription: function (skew) {
    const absSkew = Math.abs(skew);

    if (absSkew === 0) {
      return '水平视图';
    } else if (absSkew <= 15) {
      return `轻微倾斜 (${skew.toFixed(1)}°)`;
    } else if (absSkew <= 30) {
      return `中等倾斜 (${skew.toFixed(1)}°)`;
    } else if (absSkew <= 45) {
      return `较大倾斜 (${skew.toFixed(1)}°)`;
    } else if (absSkew <= 60) {
      return `严重倾斜 (${skew.toFixed(1)}°)`;
    } else {
      return `极端倾斜 (${skew.toFixed(1)}°)`;
    }
  },

  // 初始化地图标记聚合
  initMarkerCluster: function (options) {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 设置默认选项
    const defaultOptions = {
      enableDefaultStyle: true,
      zoomOnClick: true,
      gridSize: 60,
      maxZoom: 16,
      minClusterSize: 2,
      styles: [
        {
          url: '/image/pause.png',
          size: { width: 40, height: 40 },
          textColor: '#ffffff',
          textSize: 12
        },
        {
          url: '/image/plus.png',
          size: { width: 50, height: 50 },
          textColor: '#ffffff',
          textSize: 14
        },
        {
          url: '/image/stop.png',
          size: { width: 60, height: 60 },
          textColor: '#ffffff',
          textSize: 16
        }
      ]
    };

    // 合并选项
    const clusterOptions = Object.assign({}, defaultOptions, options || {});

    that.mapContext.initMarkerCluster({
      enableDefaultStyle: clusterOptions.enableDefaultStyle,
      zoomOnClick: clusterOptions.zoomOnClick,
      gridSize: clusterOptions.gridSize,
      maxZoom: clusterOptions.maxZoom,
      minClusterSize: clusterOptions.minClusterSize,
      styles: clusterOptions.styles,
      success: function (res) {
        that.showResult(
          res
        );

      },
      fail: function (err) {
        that.showResult(`标记聚合初始化失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('标记聚合初始化失败:', err);
      }
    });
  },

  // 标记点沿路径移动
  moveAlong: function (markerId, path, options) {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 验证参数
    if (!markerId && markerId !== 0) {
      that.showResult('标记点ID不能为空');
      return;
    }

    // 确保markerId是数字类型
    const numericMarkerId = Number(markerId);
    if (isNaN(numericMarkerId)) {
      that.showResult('标记点ID必须是数字');
      return;
    }

    if (!path || !Array.isArray(path) || path.length === 0) {
      that.showResult('移动路径不能为空');
      return;
    }

    // 验证路径点格式
    for (let i = 0; i < path.length; i++) {
      const point = path[i];
      if (!point.latitude || !point.longitude) {
        that.showResult(`第${i + 1}个路径点缺少经纬度信息`);
        return;
      }
    }

    // 设置默认选项
    const defaultOptions = {
      duration: 5000,        // 移动持续时间（毫秒）
      autoRotate: false,     // 是否自动旋转
      success: function (res) {
        that.showResult(`标记点开始沿路径移动`);
      },
      fail: function (err) {
        that.showResult(`标记点移动失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('标记点移动失败:', err);
      }
    };

    // 合并选项
    const moveOptions = Object.assign({}, defaultOptions, options || {});

    that.mapContext.moveAlong({
      markerId: numericMarkerId,
      path: path,
      duration: moveOptions.duration,
      autoRotate: moveOptions.autoRotate,
      success: moveOptions.success,
      fail: moveOptions.fail
    });
  },


  // 打开系统默认地图应用
  openMapApp: function (latitude, longitude, options) {
    const that = this;

    // 验证参数
    if (!latitude || !longitude) {
      that.showResult('经纬度不能为空');
      return;
    }

    // 验证经纬度格式
    const lat = Number(latitude);
    const lng = Number(longitude);

    if (isNaN(lat) || isNaN(lng)) {
      that.showResult('经纬度必须是数字');
      return;
    }

    if (lat < -90 || lat > 90) {
      that.showResult('纬度必须在-90到90之间');
      return;
    }

    if (lng < -180 || lng > 180) {
      that.showResult('经度必须在-180到180之间');
      return;
    }

    // 设置默认选项
    const defaultOptions = {
      name: '',              // 地点名称
      address: '',           // 地址
      scale: 18,             // 缩放级别
      success: function (res) {
        that.showResult(
          res
        );

      },
      fail: function (err) {
        that.showResult(`打开系统地图应用失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('打开系统地图应用失败:', err);
      }
    };

    // 合并选项
    const mapOptions = Object.assign({}, defaultOptions, options || {});

    wx.openLocation({
      latitude: lat,
      longitude: lng,
      name: mapOptions.name,
      address: mapOptions.address,
      scale: mapOptions.scale,
      success: mapOptions.success,
      fail: mapOptions.fail
    });
  },

  // 移除地图弧线
  removeArc: function (arcId) {
    const that = this;


    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 验证参数
    if (!arcId && arcId !== 0) {
      that.showResult('弧线ID不能为空');
      return;
    }

    // 确保arcId是数字类型
    const numericArcId = Number(arcId);
    if (isNaN(numericArcId)) {
      that.showResult('弧线ID必须是数字');
      return;
    }


    // 先找到要移除的弧线数据
    const currentArcs = that.data.arcs || [];
    const arcToRemove = currentArcs.find(arc => arc.id === numericArcId);

    if (!arcToRemove) {
      that.showResult(`未找到ID为${numericArcId}的弧线`);
      return;
    }


    // 移除对应的polyline
    if (arcToRemove.polylineId !== undefined) {
      const currentPolylines = that.data.polyline || [];
      const updatedPolylines = currentPolylines.filter((polyline, index) => index !== arcToRemove.polylineId);
      that.setData({
        polyline: updatedPolylines
      });
    }

    // 移除对应的markers（起点和终点）
    if (arcToRemove.startMarkerId !== undefined && arcToRemove.endMarkerId !== undefined) {
      const currentMarkers = that.data.markers || [];
      const updatedMarkers = currentMarkers.filter((marker, index) =>
        index !== arcToRemove.startMarkerId && index !== arcToRemove.endMarkerId
      );
      that.setData({
        markers: updatedMarkers
      });
    }

    // 从数据中移除对应的弧线
    const updatedArcs = currentArcs.filter(arc => arc.id !== numericArcId);
    that.setData({
      arcs: updatedArcs
    });

    that.showResult(
      `弧线移除成功\n` +
      `弧线ID: ${numericArcId}\n` +
      `移除时间: ${new Date().toLocaleString()}\n` +
      `已移除polyline和markers`
    );

  },

  // 移除自定义图层
  removeCustomLayer: function (layerId) {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 验证参数
    if (!layerId && layerId !== 0) {
      that.showResult('图层ID不能为空');
      return;
    }

    // 确保layerId是字符串类型
    const stringLayerId = String(layerId);

    that.mapContext.removeCustomLayer({
      layerId: stringLayerId,
      success: function (res) {
        that.showResult(
          res
        );

        // 从数据中移除对应的图层
        const currentLayers = that.data.customLayers || [];
        const updatedLayers = currentLayers.filter(layer => String(layer.id) !== stringLayerId);

        that.setData({
          customLayers: updatedLayers
        });

      },
      fail: function (err) {
        that.showResult(`自定义图层移除失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('自定义图层移除失败:', err);
      }
    });
  },

  // 移除地面覆盖物
  removeGroundOverlay: function (overlayId) {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 验证参数
    if (!overlayId && overlayId !== 0) {
      that.showResult('覆盖物ID不能为空');
      return;
    }

    // 确保overlayId是字符串类型
    const stringOverlayId = String(overlayId);

    that.mapContext.removeGroundOverlay({
      id: stringOverlayId,
      success: function (res) {
        that.showResult(
          res
        );

        // 从数据中移除对应的覆盖物
        const currentOverlays = that.data.groundOverlays || [];
        const updatedOverlays = currentOverlays.filter(overlay => String(overlay.id) !== stringOverlayId);

        that.setData({
          groundOverlays: updatedOverlays
        });

      },
      fail: function (err) {
        that.showResult(`地面覆盖物移除失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('地面覆盖物移除失败:', err);
      }
    });
  },

  // 移除视觉图层
  removeVisualLayer: function (layerId) {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 验证参数
    if (!layerId && layerId !== 0) {
      that.showResult('视觉图层ID不能为空');
      return;
    }

    // 确保layerId是字符串类型
    const stringLayerId = String(layerId);

    that.mapContext.removeVisualLayer({
      layerId: stringLayerId,
      success: function (res) {
        that.showResult(
          res
        );

        // 从数据中移除对应的视觉图层
        const currentVisualLayers = that.data.visualLayers || [];
        const updatedVisualLayers = currentVisualLayers.filter(layer => String(layer.id) !== stringLayerId);

        that.setData({
          visualLayers: updatedVisualLayers
        });

      },
      fail: function (err) {
        that.showResult(`视觉图层移除失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('视觉图层移除失败:', err);
      }
    });
  },

  // 设置地图显示范围，包含指定点集
  includePoints: function (points, padding) {
    const that = this;

    // 检查地图上下文
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 验证参数
    if (!points || !Array.isArray(points) || points.length === 0) {
      that.showResult('点集不能为空');
      return;
    }

    // 验证点集格式
    for (let i = 0; i < points.length; i++) {
      const point = points[i];
      if (!point.latitude || !point.longitude) {
        that.showResult(`第${i + 1}个点缺少经纬度信息`);
        return;
      }
    }

    // 设置默认边距
    const defaultPadding = padding || [20, 20, 20, 20];

    that.mapContext.includePoints({
      points: points,
      padding: defaultPadding,
      success: function (res) {
        that.showResult(
          res
        );

        // 保存当前包含的点集
        that.setData({
          includePoints: points
        });

      },
      fail: function (err) {
        that.showResult(`调整地图范围失败: ${err.errMsg || JSON.stringify(err)}`);
        console.error('调整地图范围失败:', err);
      }
    });
  },

  // 获取缩放级别描述
  getScaleDescription: function (scale) {
    if (scale <= 5) {
      return '世界级视图';
    } else if (scale <= 8) {
      return '国家级视图';
    } else if (scale <= 10) {
      return '省级视图';
    } else if (scale <= 12) {
      return '市级视图';
    } else if (scale <= 14) {
      return '区县级视图';
    } else if (scale <= 16) {
      return '街道级视图';
    } else if (scale <= 18) {
      return '建筑级视图';
    } else if (scale <= 20) {
      return '详细建筑级视图';
    } else {
      return '超详细视图';
    }
  },

  // 获取旋转角度描述
  getRotateDescription: function (angle) {
    // 将角度标准化到 0-360 度范围
    const normalizedAngle = ((angle % 360) + 360) % 360;

    if (normalizedAngle === 0) {
      return '正北方向';
    } else if (normalizedAngle < 90) {
      return `东北方向 (${normalizedAngle.toFixed(1)}°)`;
    } else if (normalizedAngle === 90) {
      return '正东方向';
    } else if (normalizedAngle < 180) {
      return `东南方向 (${(180 - normalizedAngle).toFixed(1)}°)`;
    } else if (normalizedAngle === 180) {
      return '正南方向';
    } else if (normalizedAngle < 270) {
      return `西南方向 (${(normalizedAngle - 180).toFixed(1)}°)`;
    } else if (normalizedAngle === 270) {
      return '正西方向';
    } else {
      return `西北方向 (${(360 - normalizedAngle).toFixed(1)}°)`;
    }
  },

  // 显示操作结果
  showResult: function (message) {
    this.setData({
      result: message
    });
  },

  // 表单数据变化事件
  getFormData: function (e) {
    this.setData({
      formData: e.detail
    });
  },



  // 测试添加视觉图层
  testAddVisualLayer: function () {
    // 检查地图上下文是否初始化
    if (!this.mapContext) {
      this.showResult('地图上下文未初始化');
      return;
    }

    // 准备测试数据
    const visualLayerParams = {
      id: 'test_visual_layer_' + Date.now(), // 唯一ID
      zIndex: 20, // 图层层级
      visible: true, // 是否可见
      data: {
        // 示例数据 - 可以根据实际需求添加
        points: [
          { latitude: this.data.currentLocation.latitude + 0.005, longitude: this.data.currentLocation.longitude - 0.005 },
          { latitude: this.data.currentLocation.latitude + 0.01, longitude: this.data.currentLocation.longitude + 0.01 }
        ]
      },
      style: {
        // 示例样式 - 可以根据实际需求添加
        color: '#FF0000',
        size: 10
      }
    };

    // 调用addVisualLayer方法添加视觉图层
    const result = this.addVisualLayer(visualLayerParams);
    this.showResult(result);
  },

  // 测试清除线条
  testEraseLines: function () {
    // 检查地图上下文是否初始化
    if (!this.mapContext) {
      this.showResult('地图上下文未初始化');
      return;
    }

    // 调用eraseLines方法清除线条
    const result = this.mapContext.eraseLines();
    this.showResult({ result: result });
  },

  // 测试添加地面覆盖物
  testAddGroundOverlay: function () {
    // 检查地图上下文是否初始化
    if (!this.mapContext) {
      this.showResult('地图上下文未初始化');
      return;
    }

    // 准备测试数据
    const groundOverlayParams = {
      id: Date.now(), // 唯一ID（数字类型）
      src: '/image/icon_cloud.png', // 假设存在的图片路径
      bounds: {
        sw: { latitude: 39.90, longitude: 116.40 }, // 西南角坐标
        ne: { latitude: 39.92, longitude: 116.43 }  // 东北角坐标
      },
      zIndex: 20, // 图层层级
      opacity: 0.6, // 透明度
      rotate: 10, // 旋转角度
      visible: true // 是否可见
    };

    // 调用addGroundOverlay方法添加地面覆盖物
    const result = this.addGroundOverlay(groundOverlayParams);
    this.showResult(result);
  },

  // 测试执行可视化图层指令
  testExecuteVisualLayerCommand: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 使用固定的图层ID
    const layerId = 'test_visual_layer_' + Date.now();

    // 先创建一个测试图层
    const testLayerParams = {
      id: layerId,
      zIndex: 20,
      visible: true,
      data: {
        points: [
          { latitude: that.data.currentLocation.latitude + 0.005, longitude: that.data.currentLocation.longitude - 0.005 }
        ]
      },
      style: {
        color: '#FF0000',
        size: 10
      }
    };

    // 添加测试图层
    that.addVisualLayer(testLayerParams);

    // 准备测试数据
    const commandParams = {
      layerId: layerId, // 使用相同的图层ID
      command: 'updateStyle', // 指令名称
      params: {
        color: '#ff0000', // 样式参数
        opacity: 0.8
      }
    };

    // 调用executeVisualLayerCommand方法执行指令
    const result = that.executeVisualLayerCommand(commandParams);
    that.showResult(result);
  },

  // 测试事件监听功能
  testEventListeners: function () {
    const that = this;

    // 注册测试事件监听器
    that.addEventListener('visualLayerUpdate', function (eventData) {
      that.showResult(`事件监听器收到更新: ${eventData.layerId}`);
    });

    that.addEventListener('visualLayerCommand', function (eventData) {
      that.showResult(`事件监听器收到指令: ${eventData.command}`);
    });

    that.addEventListener('visualLayerError', function (eventData) {
      that.showResult(`事件监听器收到错误: ${eventData.error}`);
    });

    that.showResult('已注册测试事件监听器');
  },

  // 测试多种可视化图层指令
  testMultipleVisualLayerCommands: function () {
    const that = this;

    // 首先确保有测试图层
    if (!that.data.visualLayers || that.data.visualLayers.length === 0) {
      that.testAddVisualLayer();
    }

    // 使用固定的图层ID，确保能找到对应的图层
    const layerId = 'test_visual_layer_' + Date.now();

    // 先创建一个测试图层
    const testLayerParams = {
      id: layerId,
      zIndex: 20,
      visible: true,
      data: {
        points: [
          { latitude: that.data.currentLocation.latitude + 0.005, longitude: that.data.currentLocation.longitude - 0.005 },
          { latitude: that.data.currentLocation.latitude + 0.01, longitude: that.data.currentLocation.longitude + 0.01 }
        ]
      },
      style: {
        color: '#FF0000',
        size: 10
      }
    };

    // 添加测试图层
    that.addVisualLayer(testLayerParams);

    // 测试不同的指令，使用相同的图层ID
    const commands = [
      {
        layerId: layerId,
        command: 'updateStyle',
        params: { color: '#00ff00', size: 15 }
      },
      {
        layerId: layerId,
        command: 'setVisible',
        params: { visible: false }
      },
      {
        layerId: layerId,
        command: 'setZIndex',
        params: { zIndex: 100 }
      },
      {
        layerId: layerId,
        command: 'updateData',
        params: { points: [{ lat: 39.9, lng: 116.4 }] }
      }
    ];

    commands.forEach((cmd, index) => {
      setTimeout(() => {
        that.executeVisualLayerCommand(cmd);
      }, index * 500); // 每500ms执行一个指令
    });

    that.showResult(that.executeVisualLayerCommand(commands[commands.length - 1]));
  },

  // 测试错误处理
  testVisualLayerError: function () {
    const that = this;

    // 故意传入错误的参数来触发错误事件
    const errorCommand = {
      layerId: 'non_existent_layer',
      command: 'invalid_command',
      params: { invalid: 'data' }
    };

    that.executeVisualLayerCommand(errorCommand);
    that.showResult(that.executeVisualLayerCommand(errorCommand));
  },

  // 清除事件监听器测试
  testClearEventListeners: function () {
    const that = this;

    const result = that.clearEventListeners();
    that.showResult(result ? '已清除所有事件监听器' : '清除事件监听器失败');
  },




  fromScreenLocation: function (object) {
    const that = this;

    // 直接使用原生API
    that.mapContext.fromScreenLocation({
      x: object.x,
      y: object.y,
      success: function (result) {
        console.log(result,666);
        if (object.success && typeof object.success === 'function') {
          object.success(result);
        }
      },
      fail: function (error) {
        if (object.fail && typeof object.fail === 'function') {
          object.fail(error);
        }
      }
    });
  },

  // 测试单个屏幕坐标转换
  testSingleScreenLocation: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 测试地图中心点的屏幕坐标
    const screenPoint = { x: 500, y: 350 };

    that.fromScreenLocation({
      x: screenPoint.x,
      y: screenPoint.y,
      success: function (result) {
        console.log(result,777);
        that.showResult(
          result
        );
        console.log(result, 555);
        // 在地图上添加标记点
        that.addMarker(
          result.latitude,
          result.longitude,
          that.data.markers.length
        );
      },
      fail: function (error) {
        that.showResult(`转换失败: ${error.errMsg}`);
      }
    });
  },

  // 测试获取地图范围并添加边界标记
  testGetRegionWithMarkers: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 获取地图范围
    that.mapContext.getRegion({
      success: function (res) {
        // 在四个角添加标记点
        that.addMarker(
          res.southwest.latitude,
          res.southwest.longitude,
          '西南角',
          that.data.markers.length
        );

        that.addMarker(
          res.northeast.latitude,
          res.northeast.longitude,
          '东北角',
          that.data.markers.length
        );

        that.addMarker(
          res.southwest.latitude,
          res.northeast.longitude,
          '东南角',
          that.data.markers.length
        );

        that.addMarker(
          res.northeast.latitude,
          res.southwest.longitude,
          '西北角',
          that.data.markers.length
        );

        // 在中心点添加标记
        const centerLat = (res.southwest.latitude + res.northeast.latitude) / 2;
        const centerLng = (res.southwest.longitude + res.northeast.longitude) / 2;

        that.addMarker(
          centerLat,
          centerLng,
          '范围中心',
          that.data.markers.length
        );

        that.showResult(res);
      },
      fail: function (err) {
        that.showResult(`获取地图范围失败: ${err.errMsg || JSON.stringify(err)}`);
      }
    });
  },

  // 测试设置小范围边界
  testSetSmallBoundary: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 定义小范围边界 - 以当前位置为中心的小区域
    const currentLat = that.data.currentLocation.latitude;
    const currentLng = that.data.currentLocation.longitude;

    const smallBoundary = {
      southwest: {
        latitude: currentLat - 0.005,  // 西南角纬度
        longitude: currentLng - 0.005   // 西南角经度
      },
      northeast: {
        latitude: currentLat + 0.005,  // 东北角纬度
        longitude: currentLng + 0.005   // 东北角经度
      }
    };

    that.showResult('正在设置小范围地图边界...');

    // 调用 setBoundary 函数
    that.mapContext.setBoundary(smallBoundary);
  },


  // 测试获取地图倾斜角度
  testGetSkew: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getSkew({
      success: function (res) {
        that.showResult(
          res
        );

        // 保存倾斜角度数据
        that.setData({
          currentSkew: res
        });
      },
      fail: function (err) {
        that.showResult(`获取倾斜角度失败: ${err.errMsg || JSON.stringify(err)}`);
      }
    });
  },


  // 测试包含多个点
  testIncludeMultiplePoints: function () {
    const that = this;

    // 定义多个点（北京几个著名景点）
    const points = [
      { latitude: 39.9042, longitude: 116.4074 }, // 天安门
      { latitude: 39.9163, longitude: 116.3972 }, // 故宫
      { latitude: 39.9047, longitude: 116.4072 }, // 人民大会堂
      { latitude: 39.9043, longitude: 116.3916 }  // 国家大剧院
    ];

    that.includePoints(points, [30, 30, 30, 30]);

  },




  // 测试获取地图缩放级别
  testGetScale: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getScale({
      success: function (res) {
        const scaleData = {
          scale: res.scale,
          timestamp: Date.now()
        };

        that.showResult(
          res
        );

        // 保存缩放级别数据
        that.setData({
          currentScale: scaleData
        });
      },
      fail: function (err) {
        that.showResult(`获取缩放级别失败: ${err.errMsg || JSON.stringify(err)}`);
      }
    });
  },

  // 获取缩放级别范围描述
  getScaleRange: function (scale) {
    if (scale <= 5) {
      return '1-5级 (世界级)';
    } else if (scale <= 8) {
      return '6-8级 (国家级)';
    } else if (scale <= 10) {
      return '9-10级 (省级)';
    } else if (scale <= 12) {
      return '11-12级 (市级)';
    } else if (scale <= 14) {
      return '13-14级 (区县级)';
    } else if (scale <= 16) {
      return '15-16级 (街道级)';
    } else if (scale <= 18) {
      return '17-18级 (建筑级)';
    } else if (scale <= 20) {
      return '19-20级 (详细建筑级)';
    } else {
      return '20+级 (超详细)';
    }
  },

  // 测试获取地图旋转角度
  testGetRotate: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    that.mapContext.getRotate({
      success: function (res) {
        const rotateData = {
          rotate: res.rotate,
          timestamp: Date.now()
        };

        that.showResult(
          res
        );

        // 保存旋转角度数据
        that.setData({
          currentRotate: rotateData
        });
      },
      fail: function (err) {
        that.showResult(`获取旋转角度失败: ${err.errMsg || JSON.stringify(err)}`);
      }
    });
  },
  // 测试使用地图中心点打开位置
  testOpenLocationWithCenter: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 先获取地图中心点
    that.mapContext.getCenterLocation({
      success: function (res) {
        // 使用 gcj02 坐标系数据调用 wx.openLocation
        wx.openLocation({
          latitude: res.latitude,
          longitude: res.longitude,
          name: '地图中心点',
          address: '当前地图中心位置',
          scale: 18,
          success: function (res) {
            that.showResult(res);
          },
          fail: function (err) {
            that.showResult(`打开位置失败: ${err.errMsg || JSON.stringify(err)}`);
          }
        });
      },
      fail: function (err) {
        that.showResult(`获取地图中心点失败: ${err.errMsg || JSON.stringify(err)}`);
      }
    });
  },

  // 测试获取中心点并添加标记
  testGetCenterAndAddMarker: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 获取地图中心点
    that.mapContext.getCenterLocation({
      success: function (res) {
        // 在中心点添加标记
        that.addMarker(
          res.latitude,
          res.longitude,
          `地图中心点 (${res.latitude.toFixed(6)}, ${res.longitude.toFixed(6)})`,
          that.data.markers.length
        );

        that.showResult(that.data.markers[that.data.markers.length - 1]);

        // 保存中心点数据
        that.setData({
          currentCenterLocation: {
            latitude: res.latitude,
            longitude: res.longitude,
            coordinateType: 'gcj02',
            timestamp: Date.now()
          }
        });
      },
      fail: function (err) {
        that.showResult(`获取地图中心点失败: ${err.errMsg || JSON.stringify(err)}`);
      }
    });
  },

  // 测试移除标记点
  testRemoveMarkers: function () {
    // 检查地图上下文是否初始化
    if (!this.mapContext) {
      this.showResult('地图上下文未初始化');
      return;
    }

    // 首先添加一些标记点用于测试
    const markersToAdd = {
      markers: [
        {
          id: 'marker_to_remove_1',
          latitude: 39.90923,
          longitude: 116.397428,
          title: '可移除标记点1'
        },
        {
          id: 'marker_to_remove_2',
          latitude: 39.90923,
          longitude: 116.407428,
          title: '可移除标记点2'
        }
      ]
    };
    this.addMarkers(markersToAdd);

    // 准备测试数据
    const removeParams = {
      markerIds: ['marker_to_remove_1'] // 要移除的标记点ID数组
    };

    // 调用removeMarkers方法移除标记点
    const result = this.removeMarkers(removeParams);
    this.showResult(result);
  },

  // 测试初始化自定义标记聚合
  testInitCustomMarkerCluster: function () {
    const that = this;

    // 自定义聚合配置
    const customOptions = {
      enableDefaultStyle: true,
      zoomOnClick: true,
      gridSize: 80,
      maxZoom: 18,
      minClusterSize: 3,
      styles: [
        {
          url: '/image/pause.png',
          size: { width: 45, height: 45 },
          textColor: '#ff0000',
          textSize: 13
        },
        {
          url: '/image/plus.png',
          size: { width: 55, height: 55 },  
          textColor: '#ff0000',
          textSize: 15
        },
        {
          url: '/image/stop.png',
          size: { width: 65, height: 65 },
          textColor: '#ff0000',
          textSize: 17
        }
      ]
    };

    that.initMarkerCluster(customOptions);
  },

  // 测试标记点沿圆形路径移动
  testMoveAlongCircle: function () {
    const that = this;

    // 创建移动标记点
    const movingMarker = {
      id: 3,
      latitude: 39.9042,
      longitude: 116.4074,
      title: '圆形移动标记',
      iconPath: '/image/stop.png',
      width: 30,
      height: 30
    };

    // 设置标记点
    that.setData({
      markers: [movingMarker]
    });

    // 定义圆形路径
    const circlePath = [];
    const centerLat = 39.9042;
    const centerLng = 116.4074;
    const radius = 0.005; // 约500米半径

    // 生成圆形路径点
    for (let i = 0; i <= 360; i += 10) {
      const angle = (i * Math.PI) / 180;
      const lat = centerLat + radius * Math.cos(angle);
      const lng = centerLng + radius * Math.sin(angle);
      circlePath.push({ latitude: lat, longitude: lng });
    }

    // 开始移动
    that.moveAlong(3, circlePath, {
      duration: 10000,
      autoRotate: true
    });
  },


  // 测试更新标记点
  testUpdateMarkers: function () {
    // 检查地图上下文是否初始化
    if (!this.mapContext) {
      this.showResult('地图上下文未初始化');
      return;
    }

    // 首先添加一些标记点用于测试
    const markersToAdd = {
      markers: [
        {
          id: 'marker_to_update',
          latitude: 39.90923,
          longitude: 116.397428,
          title: '原始标记点'
        }
      ]
    };
    this.addMarkers(markersToAdd);

    // 准备测试数据
    const updateParams = {
      markers: [
        {
          id: 'marker_to_update',
          title: '已更新的标记点',
          iconPath: '/resources/images/marker.png'
        }
      ]
    };

    // 调用updateMarkers方法更新标记点
    const result = this.updateMarkers(updateParams);
    this.showResult(result);
  },
  testMoveToShanghai: function () {
    const that = this;

    that.moveToLocation(31.239663, 121.499809, {
      duration: 2000
    });
  },
  // 测试添加自定义图层
  testAddCustomLayer: function () {
    // 检查地图上下文是否初始化
    if (!this.mapContext) {
      this.showResult('地图上下文未初始化');
      return;
    }

    // 准备测试数据
    const customLayerParams = {
      id: Date.now(), // 唯一ID（数字类型）
      zIndex: 10, // 图层层级
      visible: true, // 是否可见
      // 这里可以添加render和destroy函数，但在模拟环境中可能不会被调用
      render: function () {
      },
      destroy: function () {
      }
    };

    // 调用addCustomLayer方法添加自定义图层
    const result = this.addCustomLayer(customLayerParams);
    this.showResult(result);
  },

  // 测试打开系统地图应用 - 上海外滩
  testOpenMapAppShanghai: function () {
    const that = this;
    wx.createMapContext("myMap").openMapApp({
      longitude: 102.715351,
      latitude: 25.033913,
      destination: "昆明白癜风皮肤病医院",
      success: function () {
        console.log("导航成功")
      },
      fail: function (t) {
        console.log("导航失败", t)
      }
    })
    // this.mapContext.openMapApp({
    //   latitude: 23.1296 ,
    //   longitude:113.35 ,
    //   destination: '上海外滩',
    //   success: function (res) {
    //     that.showResult(res);
    //   },
    //   fail: function (err) {
    //     that.showResult(err);
    //   }
    // });
  },

  // 测试设置地图中心点偏移
  testSetCenterOffset: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 测试设置中心点偏移到右下角
    const offsetParams = {
      offset: [0.6, 0.7], // 向右下偏移
      success: function (result) {
        that.showResult(
          result
        );
      },
      fail: function (error) {
        that.showResult(`设置中心点偏移失败: ${error.errMsg}`);
      }
    };

    that.setCenterOffset(offsetParams);
  },


  // 测试添加弧线
  testAddArc: function () {
    // 检查currentLocation是否存在
    if (!this.data.currentLocation || !this.data.currentLocation.latitude) {
      this.showResult('获取位置信息失败，请先获取位置');
      return;
    }

    // 准备测试数据
    const arcParams = {
      latitude: this.data.currentLocation.latitude, // 当前位置纬度
      longitude: this.data.currentLocation.longitude, // 当前位置经度
      radius: 500, // 半径500米
      startAngle: 0, // 起始角度0度
      endAngle: 90 // 结束角度90度（四分之一圆）
    };

    // 调用addArc方法添加弧线
    const result = this.addArc(arcParams);
    this.showResult(result);
  },







  // 显示所有图层状态
  testShowAllStatus: function () {
    const that = this;

    const currentArcs = that.data.arcs || [];
    const currentLayers = that.data.customLayers || [];
    const currentOverlays = that.data.groundOverlays || [];
    const currentVisualLayers = that.data.visualLayers || [];

    that.showResult(
      `所有图层状态:\n` +
      `弧线数量: ${currentArcs.length}\n` +
      `自定义图层数量: ${currentLayers.length}\n` +
      `地面覆盖物数量: ${currentOverlays.length}\n` +
      `视觉图层数量: ${currentVisualLayers.length}\n` +
      `自定义图层ID: ${currentLayers.map(layer => `${layer.id}(${typeof layer.id})`).join(', ')}\n` +
      `地面覆盖物ID: ${currentOverlays.map(overlay => `${overlay.id}(${typeof overlay.id})`).join(', ')}\n` +
      `视觉图层ID: ${currentVisualLayers.map(layer => `${layer.id}(${typeof layer.id})`).join(', ')}`
    );
  },

  // 测试添加和移除地面覆盖物
  testAddAndRemoveGroundOverlay: function () {
    const that = this;

    // 先添加一个地面覆盖物
    const groundOverlayParams = {
      id: Date.now(),
      src: '/image/icon_cloud.png',
      bounds: {
        sw: { latitude: 39.90, longitude: 116.40 },
        ne: { latitude: 39.92, longitude: 116.43 }
      },
      zIndex: 20,
      opacity: 0.6,
      rotate: 10,
      visible: true
    };

    const addResult = that.addGroundOverlay(groundOverlayParams);
    that.showResult(addResult);

    // 延迟1秒后移除
    setTimeout(() => {
      that.removeGroundOverlay(groundOverlayParams.id);
    }, 1000);
  },

  // 测试移除自定义图层
  testRemoveCustomLayer: function () {
    const that = this;

    // 获取第一个自定义图层ID
    const currentLayers = that.data.customLayers || [];
    if (currentLayers.length === 0) {
      that.showResult('当前没有自定义图层可以移除');
      return;
    }

    const firstLayer = currentLayers[0];

    // 直接传递ID，removeCustomLayer函数会处理类型转换
    that.removeCustomLayer(firstLayer.id);
  },

  // 测试移除地面覆盖物
  testRemoveGroundOverlay: function () {
    const that = this;

    // 获取第一个地面覆盖物ID
    const currentOverlays = that.data.groundOverlays || [];
    if (currentOverlays.length === 0) {
      that.showResult('当前没有地面覆盖物可以移除');
      return;
    }

    const firstOverlay = currentOverlays[0];

    that.removeGroundOverlay(firstOverlay.id);
  },

  // 测试移除视觉图层
  testRemoveVisualLayer: function () {
    const that = this;

    // 获取第一个视觉图层ID
    const currentVisualLayers = that.data.visualLayers || [];
    if (currentVisualLayers.length === 0) {
      that.showResult('当前没有视觉图层可以移除');
      return;
    }

    const firstVisualLayer = currentVisualLayers[0];

    // 直接传递ID，removeVisualLayer函数会处理类型转换
    that.removeVisualLayer(firstVisualLayer.id);
  },

  // 添加弧线覆盖物 - 支持.success().fail()链式调用
  addArc: function (object) {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    try {
      // 检查参数是否有效
      if (!object || !object.latitude || !object.longitude ||
        typeof object.radius !== 'number' || typeof object.startAngle !== 'number' || typeof object.endAngle !== 'number') {
        console.error('addArc参数不完整');
        return { errMsg: 'addArc参数不完整' };
      }

      // 生成弧线ID
      const arcId = object.arcId || Date.now();

      // 由于微信小程序原生地图API可能不直接支持弧线，可以通过添加多个点来模拟弧线
      const points = [];
      const numPoints = 50; // 弧线点数
      const startRad = object.startAngle * Math.PI / 180;
      const endRad = object.endAngle * Math.PI / 180;
      const angleStep = (endRad - startRad) / numPoints;

      for (let i = 0; i <= numPoints; i++) {
        const angle = startRad + angleStep * i;
        const pointLat = object.latitude + (object.radius / 111320) * Math.cos(angle); // 1度约等于111320米
        const pointLng = object.longitude + (object.radius / (111320 * Math.cos(object.latitude * Math.PI / 180))) * Math.sin(angle);
        points.push({ latitude: pointLat, longitude: pointLng });
      }

      // 添加弧线的起点和终点标记
      const startMarkerId = that.data.markers.length;
      const endMarkerId = that.data.markers.length + 1;

      that.addMarker(object.latitude + (object.radius / 111320) * Math.cos(startRad),
        object.longitude + (object.radius / (111320 * Math.cos(object.latitude * Math.PI / 180))) * Math.sin(startRad),
        '弧线起点', startMarkerId);

      that.addMarker(object.latitude + (object.radius / 111320) * Math.cos(endRad),
        object.longitude + (object.radius / (111320 * Math.cos(object.latitude * Math.PI / 180))) * Math.sin(endRad),
        '弧线终点', endMarkerId);

      // 使用polyline绘制弧线
      that.addPolyline(points);

      // 创建弧线对象并存储到数据中
      const arcData = {
        id: arcId,
        latitude: object.latitude,
        longitude: object.longitude,
        radius: object.radius,
        startAngle: object.startAngle,
        endAngle: object.endAngle,
        startMarkerId: startMarkerId,
        endMarkerId: endMarkerId,
        polylineId: that.data.polyline.length - 1,
        timestamp: Date.now(),
        visible: true
      };


      // 添加到数据中
      const currentArcs = that.data.arcs || [];
      currentArcs.push(arcData);

      that.setData({
        arcs: currentArcs
      });

      const result = {
        errMsg: '弧线添加成功',
        arcId: arcId,
        arcData: arcData
      };


      return result;
    } catch (error) {
      return { errMsg: `添加弧线异常: ${JSON.stringify(error)}` };
    }
  },

  // 批量添加标记点
  addMarkers: function (markers) {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!Array.isArray(markers)) {
      console.error('参数必须是数组类型');
      return { errMsg: '参数必须是数组类型' };
    }

    try {
      const currentMarkers = that.data.markers || [];

      // 遍历所有标记点
      markers.forEach((marker, index) => {
        if (!marker || typeof marker !== 'object') {
          console.warn(`索引为${index}的标记点数据无效，已跳过`);
          return;
        }

        // 创建标记点对象
        const newMarker = {
          id: marker.id || currentMarkers.length + index,
          latitude: marker.latitude,
          longitude: marker.longitude,
          title: marker.title || '',
          iconPath: marker.iconPath || '/image/location.png',
          width: marker.width || 30,
          height: marker.height || 30,
          ...marker // 复制其他属性
        };

        currentMarkers.push(newMarker);
      });

      that.setData({
        markers: currentMarkers
      });

      // 调用实际的MapContext.addMarkers API
      that.mapContext.addMarkers({
        markers: markers,
        success: function (res) {
          that.showResult(res);
        },
        fail: function (error) {
          that.showResult(error);
        }
      });

      // const result = { errMsg: 'addMarkers:ok' };

      // return result;
    } catch (error) {
      console.error('批量添加标记点异常', error);
      return { errMsg: `addMarkers:fail ${JSON.stringify(error)}` };
    }
  },

  // 添加视觉图层
  addVisualLayer: function (object) {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    if (!object.id || typeof object.id !== 'string') {
      console.error('缺少必要参数id');
      return { errMsg: '缺少必要参数id' };
    }

    // 设置默认值
    const zIndex = object.zIndex || 0;
    const visible = object.visible !== undefined ? object.visible : true;

    try {
      // 检查是否已经存在visualLayers数组，如果不存在则初始化
      if (!that.data.visualLayers) {
        that.setData({
          visualLayers: []
        });
      }

      // 创建视觉图层对象
      const visualLayer = {
        id: object.id,
        zIndex: zIndex,
        visible: visible,
        // 添加其他可能需要的属性
        data: object.data || {},
        style: object.style || {}
      };

      // 存储视觉图层
      const visualLayers = that.data.visualLayers;
      visualLayers.push(visualLayer);
      that.setData({
        visualLayers: visualLayers
      });

      const result = { visualLayers };

      return result;
    } catch (error) {
      console.error('添加视觉图层异常', error);
      return { errMsg: `addVisualLayer:fail ${JSON.stringify(error)}` };
    }
  },



  // 添加地面覆盖物
  addGroundOverlay: function (object) {
    const that = this;
    // 检查地图上下文
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    if (!object.id && object.id !== 0) {
      console.error('缺少必要参数id');
      return { errMsg: '缺少必要参数id' };
    }

    if (!object.src || typeof object.src !== 'string') {
      console.error('缺少必要参数src');
      return { errMsg: '缺少必要参数src' };
    }


    // 设置默认值
    const zIndex = object.zIndex || 0;
    const opacity = object.opacity !== undefined ? object.opacity : 1;
    const rotate = object.rotate || 0;
    const visible = object.visible !== undefined ? object.visible : true;

    try {
      // 在实际环境中，这里应该调用微信小程序的原生MapContext.addGroundOverlay方法
      // 由于这是一个模拟实现，我们将创建一个地面覆盖物对象并存储

      // 检查是否已经存在groundOverlays数组，如果不存在则初始化
      if (!that.data.groundOverlays) {
        that.setData({
          groundOverlays: []
        });
      }

      // 创建地面覆盖物对象
      const groundOverlay = {
        id: object.id,
        src: object.src,
        bounds: object.bounds,
        zIndex: zIndex,
        opacity: opacity,
        rotate: rotate,
        visible: visible
      };

      // 存储地面覆盖物
      const groundOverlays = that.data.groundOverlays;
      groundOverlays.push(groundOverlay);
      that.setData({
        groundOverlays: groundOverlays
      });

      return { errMsg: 'addGroundOverlay:ok' };
    } catch (error) {
      console.error('添加地面覆盖物异常', error);
      return { errMsg: `addGroundOverlay:fail ${JSON.stringify(error)}` };
    }
  },

  // 执行可视化图层指令
  executeVisualLayerCommand: function (object) {
    const that = this;
    // 检查地图上下文
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    if (!object.layerId || typeof object.layerId !== 'string') {
      console.error('缺少必要参数layerId');
      return { errMsg: '缺少必要参数layerId' };
    }

    if (!object.command || typeof object.command !== 'string') {
      console.error('缺少必要参数command');
      return { errMsg: '缺少必要参数command' };
    }

    try {
      // 在实际环境中，这里应该调用微信小程序的原生MapContext.executeVisualLayerCommand方法
      // 由于这是一个模拟实现，我们将模拟执行指令

      // 查找对应的视觉图层
      const visualLayers = that.data.visualLayers || [];
      const targetLayer = visualLayers.find(layer => layer.id === object.layerId);

      if (!targetLayer) {
        console.error('未找到指定的视觉图层');
        return { errMsg: '未找到指定的视觉图层' };
      }


      // 触发指令执行事件
      that.triggerVisualLayerCommandEvent({
        layerId: object.layerId,
        command: object.command,
        params: object.params || {},
        timestamp: Date.now()
      });

      // 根据指令类型执行相应操作
      that.handleVisualLayerCommand(object.layerId, object.command, object.params);

      return { visualLayers };
    } catch (error) {
      console.error('执行可视化图层指令异常', error);

      // 触发错误事件
      that.triggerVisualLayerErrorEvent({
        layerId: object.layerId,
        command: object.command,
        error: error.message || JSON.stringify(error),
        timestamp: Date.now()
      });

      return { errMsg: `executeVisualLayerCommand:fail ${JSON.stringify(error)}` };
    }
  },

  // 处理可视化图层指令
  handleVisualLayerCommand: function (layerId, command, params) {
    const that = this;
    const visualLayers = [...(that.data.visualLayers || [])];
    const layerIndex = visualLayers.findIndex(layer => layer.id === layerId);

    if (layerIndex === -1) return;

    const layer = visualLayers[layerIndex];

    switch (command) {
      case 'updateStyle':
        // 更新样式
        if (params) {
          layer.style = {
            ...layer.style,
            ...params
          };
        }
        break;

      case 'updateData':
        // 更新数据
        if (params) {
          layer.data = {
            ...layer.data,
            ...params
          };
        }
        break;

      case 'setVisible':
        // 设置可见性
        if (typeof params.visible === 'boolean') {
          layer.visible = params.visible;
        }
        break;

      case 'setZIndex':
        // 设置层级
        if (typeof params.zIndex === 'number') {
          layer.zIndex = params.zIndex;
        }
        break;

      case 'remove':
        // 移除图层
        visualLayers.splice(layerIndex, 1);
        break;

      default:
        console.warn(`未知的可视化图层指令: ${command}`);
    }

    // 更新数据
    that.setData({
      visualLayers: visualLayers
    });

    // 触发更新事件
    that.triggerVisualLayerUpdateEvent({
      layerId: layerId,
      command: command,
      data: layer,
      timestamp: Date.now()
    });
  },

  // 触发可视化图层指令事件
  triggerVisualLayerCommandEvent: function (eventData) {
    const that = this;

    if (that.mapContext && typeof that.mapContext.triggerEvent === 'function') {
      that.mapContext.triggerEvent('visualLayerCommand', eventData);
    } else if (that.eventListeners && that.eventListeners.visualLayerCommand) {
      // 模拟环境下手动触发事件
      that.eventListeners.visualLayerCommand.forEach(callback => {
        try {
          callback(eventData);
        } catch (error) {
          console.error('事件回调执行失败:', error);
        }
      });
    }
  },

  // 触发可视化图层更新事件
  triggerVisualLayerUpdateEvent: function (eventData) {
    const that = this;

    if (that.mapContext && typeof that.mapContext.triggerEvent === 'function') {
      that.mapContext.triggerEvent('visualLayerUpdate', eventData);
    } else if (that.eventListeners && that.eventListeners.visualLayerUpdate) {
      // 模拟环境下手动触发事件
      that.eventListeners.visualLayerUpdate.forEach(callback => {
        try {
          callback(eventData);
        } catch (error) {
          console.error('事件回调执行失败:', error);
        }
      });
    }
  },

  // 触发可视化图层错误事件
  triggerVisualLayerErrorEvent: function (eventData) {
    const that = this;

    if (that.mapContext && typeof that.mapContext.triggerEvent === 'function') {
      that.mapContext.triggerEvent('visualLayerError', eventData);
    } else if (that.eventListeners && that.eventListeners.visualLayerError) {
      // 模拟环境下手动触发事件
      that.eventListeners.visualLayerError.forEach(callback => {
        try {
          callback(eventData);
        } catch (error) {
          console.error('事件回调执行失败:', error);
        }
      });
    }
  },

  // 注册事件监听器
  addEventListener: function (eventType, callback) {
    const that = this;

    if (!that.eventListeners) {
      that.eventListeners = {
        visualLayerUpdate: [],
        visualLayerCommand: [],
        visualLayerError: []
      };
    }

    if (that.eventListeners[eventType] && typeof callback === 'function') {
      that.eventListeners[eventType].push(callback);
      return true;
    }

    console.error(`无法注册${eventType}事件监听器`);
    return false;
  },

  // 注销事件监听器
  removeEventListener: function (eventType, callback) {
    const that = this;

    if (that.eventListeners && that.eventListeners[eventType]) {
      const index = that.eventListeners[eventType].indexOf(callback);
      if (index !== -1) {
        that.eventListeners[eventType].splice(index, 1);
        return true;
      }
    }

    console.warn(`未找到${eventType}事件监听器`);
    return false;
  },

  // 清除所有事件监听器
  clearEventListeners: function (eventType) {
    const that = this;

    if (eventType) {
      if (that.eventListeners && that.eventListeners[eventType]) {
        that.eventListeners[eventType] = [];
        return true;
      }
    } else {
      // 清除所有事件监听器
      if (that.eventListeners) {
        Object.keys(that.eventListeners).forEach(key => {
          that.eventListeners[key] = [];
        });
        return true;
      }
    }

    return false;
  },

  // 移除标记点
  removeMarkers: function (object) {
    const that = this;
    // 检查地图上下文
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    if (!Array.isArray(object.markerIds)) {
      console.error('markerIds必须是数组类型');
      return { errMsg: 'markerIds必须是数组类型' };
    }

    try {
      // 获取当前标记点
      const markers = that.data.markers || [];

      // 过滤掉要移除的标记点
      const remainingMarkers = markers.filter(marker =>
        !object.markerIds.includes(marker.id)
      );

      that.setData({
        markers: remainingMarkers
      });

      // 调用实际的MapContext.removeMarkers API
      that.mapContext.removeMarkers({
        markerIds: object.markerIds,
        success: function (res) {
          that.showResult(res);
        },
        fail: function (error) {
          that.showResult(error);
        }
      });

      return { errMsg: 'removeMarkers:ok' };
    } catch (error) {
      console.error('移除标记点异常', error);
      return { errMsg: `removeMarkers:fail ${JSON.stringify(error)}` };
    }
  },

  // 更新标记点
  updateMarkers: function (object) {
    const that = this;
    // 检查地图上下文
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    if (!Array.isArray(object.markers)) {
      console.error('markers必须是数组类型');
      return { errMsg: 'markers必须是数组类型' };
    }

    try {
      // 获取当前标记点
      const markers = [...(that.data.markers || [])];

      // 更新标记点
      object.markers.forEach(updateMarker => {
        if (!updateMarker.id) return;

        const index = markers.findIndex(marker => marker.id === updateMarker.id);
        if (index !== -1) {
          // 合并更新属性
          markers[index] = {
            ...markers[index],
            ...updateMarker
          };
        }
      });

      that.setData({
        markers: markers
      });

      // 调用实际的MapContext.updateMarkers API
      that.mapContext.updateMarkers({
        markers: object.markers,
        success: function (res) {
          that.showResult(res);
        },
        fail: function (error) {
          that.showResult(error);
        }
      });

      return { errMsg: 'updateMarkers:ok' };
    } catch (error) {
      console.error('更新标记点异常', error);
      return { errMsg: `updateMarkers:fail ${JSON.stringify(error)}` };
    }
  },

  // 添加自定义图层
  addCustomLayer: function (object) {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    if (!object.id && object.id !== 0) {
      console.error('缺少必要参数id');
      return { errMsg: '缺少必要参数id' };
    }

    // 设置默认值
    const zIndex = object.zIndex || 0;
    const visible = object.visible !== undefined ? object.visible : true;

    try {
      // 在实际环境中，这里应该调用微信小程序的原生MapContext.addCustomLayer方法
      // 由于这是一个模拟实现，我们将创建一个自定义图层对象并存储

      // 检查是否已经存在customLayers数组，如果不存在则初始化
      if (!that.data.customLayers) {
        that.setData({
          customLayers: []
        });
      }

      // 创建自定义图层对象
      const customLayer = {
        id: object.id,
        zIndex: zIndex,
        visible: visible,
        // 添加其他可能需要的属性
        render: object.render || null,
        destroy: object.destroy || null
      };

      // 存储自定义图层
      const customLayers = that.data.customLayers;
      customLayers.push(customLayer);
      that.setData({
        customLayers: customLayers
      });

      const result = { customLayers };
      return result;
    } catch (error) {
      console.error('添加自定义图层异常', error);
      return { errMsg: `addCustomLayer:fail ${JSON.stringify(error)}` };
    }
  },

  // 设置地图中心点偏移
  setCenterOffset: function (object) {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      console.error('地图上下文未初始化');
      return { errMsg: '地图上下文未初始化' };
    }

    // 参数验证
    if (!object || typeof object !== 'object') {
      console.error('参数必须是对象类型');
      return { errMsg: '参数必须是对象类型' };
    }

    // 验证偏移值
    if (!Array.isArray(object.offset) || object.offset.length !== 2) {
      console.error('offset必须是包含两个元素的数组 [x, y]');
      return { errMsg: 'offset必须是包含两个元素的数组 [x, y]' };
    }

    const [x, y] = object.offset;

    // 验证偏移值范围 (0.25 ~ 0.75)
    if (typeof x !== 'number' || typeof y !== 'number') {
      console.error('偏移值必须是数字类型');
      return { errMsg: '偏移值必须是数字类型' };
    }

    if (x < 0.25 || x > 0.75 || y < 0.25 || y > 0.75) {
      console.error('偏移值必须在0.25到0.75之间');
      return { errMsg: '偏移值必须在0.25到0.75之间' };
    }

    try {
      // 在实际环境中，这里应该调用微信小程序的原生MapContext.setCenterOffset方法
      // 由于这是一个模拟实现，我们将更新本地数据

      const newCenterOffset = [x, y];

      // 更新中心点偏移数据
      that.setData({
        centerOffset: newCenterOffset
      });

      const result = {
        errMsg: 'setCenterOffset:ok',
        centerOffset: newCenterOffset,
        description: `地图中心点偏移已设置为 [${x.toFixed(2)}, ${y.toFixed(2)}]`
      };


      // 调用成功回调
      if (object.success && typeof object.success === 'function') {
        object.success(result);
      }

      return result;
    } catch (error) {
      console.error('设置地图中心点偏移异常', error);
      const errorResult = { errMsg: `setCenterOffset:fail ${JSON.stringify(error)}` };

      // 调用失败回调
      if (object.fail && typeof object.fail === 'function') {
        object.fail(errorResult);
      }

      return errorResult;
    }
  },

  // 设置定位标记图标
setLocMarkerIcon: function (object) {
  const that = this;

  // 检查地图上下文是否初始化
  if (!that.mapContext) {
    console.error('地图上下文未初始化');
    return { errMsg: '地图上下文未初始化' };
  }

  // 参数验证
  if (!object || typeof object !== 'object') {
    console.error('参数必须是对象类型');
    return { errMsg: '参数必须是对象类型' };
  }

  // 验证图标路径
  if (!object.iconPath || typeof object.iconPath !== 'string') {
    console.error('iconPath必须是字符串类型');
    return { errMsg: 'iconPath必须是字符串类型' };
  }

  // 验证图标尺寸
  const width = object.width || 30;
  const height = object.height || 30;

  if (typeof width !== 'number' || typeof height !== 'number') {
    console.error('width和height必须是数字类型');
    return { errMsg: 'width和height必须是数字类型' };
  }

  if (width <= 0 || height <= 0) {
    console.error('width和height必须大于0');
    return { errMsg: 'width和height必须大于0' };
  }

  // 直接使用原生API
  that.mapContext.setLocMarkerIcon({
    iconPath: object.iconPath,
    width: width,
    height: height,
    success: function(result) {
      // 更新本地数据
      that.setData({
        locMarkerIcon: {
          iconPath: object.iconPath,
          width: width,
          height: height
        }
      });
      
      if (object.success && typeof object.success === 'function') {
        object.success(result);
      }
    },
    fail: function(error) {
      if (object.fail && typeof object.fail === 'function') {
        object.fail(error);
      }
    }
  });
},
  // 测试设置定位标记图标
  testSetLocMarkerIcon: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 测试设置定位标记图标
    const iconParams = {
      iconPath: '/image/icon_cloud_HL.png',
      width: 40,
      height: 40,
      success: function (result) {
        that.showResult(
          result
        );
      },
      fail: function (error) {
        that.showResult(`设置定位标记图标失败: ${error.errMsg}`);
      }
    };

    that.setLocMarkerIcon(iconParams);
  },


  // 测试标记点移动动画 - 慢速移动
  testTranslateMarkerSlow: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 检查是否有标记点
    const markers = that.data.markers || [];
    if (markers.length === 0) {
      that.showResult('请先添加标记点');
      return;
    }

    // 使用第一个标记点进行测试
    const marker = markers[0];
    const currentLocation = that.data.currentLocation;

    if (!currentLocation || !currentLocation.latitude) {
      that.showResult('请先获取位置信息');
      return;
    }

    // 慢速移动到指定位置
    const translateParams = {
      markerId: marker.id,
      destination: {
        latitude: currentLocation.latitude + 0.20,
        longitude: currentLocation.longitude + 0.20
      },
      duration: 100000, // 慢速移动
      autoRotate: true,
      success: function (result) {
        that.showResult(
          result
        );
      },
      fail: function (error) {
        that.showResult(
          error
        );
      }
    };

    that.translateMarker(translateParams);
  },

  // 测试更新地面覆盖物
  testUpdateGroundOverlay: function () {
    const that = this;

    // 检查地图上下文是否初始化
    if (!that.mapContext) {
      that.showResult('地图上下文未初始化');
      return;
    }

    // 检查是否有地面覆盖物
    const groundOverlays = that.data.groundOverlays || [];
    if (groundOverlays.length === 0) {
      that.showResult('请先添加地面覆盖物');
      return;
    }

    // 使用第一个地面覆盖物进行测试
    const overlay = groundOverlays[0];

    // 更新地面覆盖物属性
    const updateParams = {
      id: overlay.id,
      opacity: 0.8, // 更新透明度
      rotate: 45,   // 更新旋转角度
      visible: true, // 确保可见
      success: function (result) {
        that.showResult(result
        );
      },
      fail: function (error) {
        that.showResult(
          error
        );
      }
    };

    that.updateGroundOverlay(updateParams);
  },
});